var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var api = frameElement.api;
var queryurl = config.BASEPATH+'sort/allot/page';
var _height = (api.config.height-132)/2-20,_width = (api.config.width-34);//获取弹出框弹出宽、高
var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择配货门店',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:false,module:'allot'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#at_shop_code").val(selected.sp_code);
				$("#shop_name").val(selected.sp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#at_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	formatGapAmount:function(val, opt, row){
		return row.at_applyamount-row.at_sendamount;
	},
	formatApplyMoney:function(val, opt, row){
		if(row.atl_unitprice == undefined){
			return PriceLimit.formatByDistribute(val);
		}
		return PriceLimit.formatByDistribute(row.atl_unitprice * row.atl_applyamount);
	},
	formatSendMoney:function(val, opt, row){
		if(row.atl_unitprice == undefined){
			return PriceLimit.formatByDistribute(val);
		}
		return PriceLimit.formatByDistribute(row.atl_unitprice * row.atl_sendamount);
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initDetailGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		this.$_type = $("#type").cssRadio({ callback: function($_obj){
			$("#at_type").val($_obj.find("input").val());
		}});
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'at_shop_code',label:'',index: 'at_shop_code',hidden:true},
	    	{name: 'at_number',label:'单据编号',index: 'at_number',width:150},
	    	{name: 'at_date',label:'日期',index: 'at_date',width:80},
	    	{name: 'shop_name',label:'店铺',index: 'at_shop_code',width:120},
	    	{name: 'at_manager',label:'经办人',index: 'at_manager',width:100},
	    	{name: 'at_applyamount',label:'申请',index: 'at_applyamount',width:80,align:'right'},
	    	{name: 'at_sendamount',label:'实发',index: 'at_sendamount',width:80,align:'right'},
	    	{name: 'sub_amount',label:'相差',index: 'at_applyamount-at_sendamount',width:80,align:'right',formatter: handle.formatGapAmount},
	    	{name: 'at_applymoney',label:'申请金额',index: 'at_applymoney',width:80,align:'right',formatter: PriceLimit.formatByDistribute},
	    	{name: 'at_sendmoney',label:'实发金额',index: 'at_sendmoney',width:80,align:'right',formatter: PriceLimit.formatByDistribute}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: _width,
			height: _height-50,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'at_id'  //图标ID
			},
			loadComplete: function(data){
				$("#detailGrid").clearGridData();
				THISPAGE.detailGridTotal();
			},
			loadError: function(xhr, status, error){		
			},
			onSelectRow: function (rowid, status) {
                var rowData = $("#grid").jqGrid("getRowData", rowid);
                THISPAGE.reloadDetailData(rowData.at_number);
            },
			ondblClickRow: function (rowid, iRow, iCol, e) {
				
            }
	    });
	},
	detailGridTotal:function(){
    	var grid=$('#detailGrid');
		var atl_applyamount=grid.getCol('atl_applyamount',false,'sum');
		var atl_sendamount=grid.getCol('atl_sendamount',false,'sum');
		var atl_applymoney=grid.getCol('atl_applymoney',false,'sum');
		var atl_sendmoney=grid.getCol('atl_sendmoney',false,'sum');
    	grid.footerData('set',{atl_applyamount:atl_applyamount,
					    		atl_sendamount:atl_sendamount,
					    		atl_applymoney:atl_applymoney,
					    		atl_sendmoney:atl_sendmoney});
    },
	initDetailGrid:function(){
		var colModel = [
		    {label:'',name: 'atl_pd_code', index: 'atl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'cr_name', width: 60},
	    	{label:'尺码',name: 'sz_name', index: 'sz_name', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'br_name', width: 60},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'申请数量',name: 'atl_applyamount', index: 'atl_applyamount', width: 70,align:'right',sorttype: 'int'},
	    	{label:'实发数量',name: 'atl_sendamount', index: 'atl_sendamount', width: 70,align:'right',sorttype: 'int'},
	    	{label:'配送价',name: 'atl_unitprice', index: 'atl_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByDistribute},
	    	{label:'申请金额',name: 'atl_applymoney', index: 'atl_applymoney', width: 80,align:'right',sorttype: 'float',formatter: handle.formatApplyMoney},
	    	{label:'实发金额',name: 'atl_sendmoney', index: 'atl_sendmoney', width: 80,align:'right',sorttype: 'float',formatter: handle.formatSendMoney}
	    ];
		$('#detailGrid').jqGrid({
			loadonce:true,
			datatype: 'local',
			width: _width,
			height: _height-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#detailPage',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:true,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'atl_id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.detailGridTotal();
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'at_type='+$("#at_type").val();
		params += '&allot_up='+$("#allot_up").val();
		params += '&at_isdraft=0';
		params += '&at_ar_state=4';
		params += '&begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&at_shop_code='+$("#at_shop_code").val();
		params += '&at_number='+Public.encodeURI($("#at_number").val());
		return params;
	},
	reset:function(){
		$("#at_shop_code").val("");
		$("#at_number").val("");
		$("#shop_name").val("");
		THISPAGE.$_date.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	reloadDetailData:function(number){
		var querydetailurl = config.BASEPATH+'sort/allot/detail_list/'+number;
		$("#detailGrid").jqGrid('setGridParam',{datatype:"json",page:1,url:querydetailurl}).trigger("reloadGrid");
	},
	initEvent:function(){
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
	}
};

function doSelect(){
	var selectedId = $("#grid").jqGrid('getGridParam', 'selrow');
	if(selectedId == null || selectedId == ""){
		Public.tips({type: 2, content : "请选择单据！"});
		return false;
	}
	var rowIds = $("#detailGrid").jqGrid('getGridParam', 'selarrrow');
    if (rowIds.length == 0) {
    	Public.tips({type: 2, content : "请选择单据明细!"});
        return false;
    }
    var rowData = $("#grid").jqGrid("getRowData", selectedId);
    var detailDatas = [];
	for (var i = 0; i < rowIds.length; i++) {
		detailDatas.push($("#detailGrid").jqGrid("getRowData", rowIds[i]));
	}
	return {mainData:rowData,detailIds:rowIds,detailDatas:detailDatas};
}

THISPAGE.init();